import { configDetail, addedConfig, updateConfig } from '@/api/system/tbSysConfig';
export default {
	props: {
		value: { type: Boolean, default: false },
		handType: { type: String, default: '' },
		dataId: String,
		type: String,
	},
	components: {},
	data() {
		return {
			loading: false,
			visible: this.value,
			formData: {},
			originalName: ''
		}
	},
	computed: {
		addOrEdit() {
			return !this.dataId;
		},
		dialogType() {
			return this.addOrEdit ? '新增' : '修改';
		},
		isAddSub() {
			return !this.addOrEdit && this.handType === 'add';
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.originalName = '';
			this.$nextTick(async () => {
				this.$refs['form'].resetFields();
				if (this.addOrEdit) {
					this.formData = {};
				} else if (this.isAddSub) {
					this.formData = { pid: this.dataId };
				} else {
					this.formData = await this.getConfigDetail(this.dataId);
					this.originalName = this.$lodash.cloneDeep(this.formData.name);
				}
			})
		}
	},
	methods: {
		//获取配置详情
		async getConfigDetail(id) {
			let result = await configDetail(id).then((res) => res.data);
			if (result.code === '0') {
				let datas = !!result.data && result.data.length > 0 ? result.data[0] : {};
				return Promise.resolve(datas);
			}
		},

		//判断是否存在
		judgeNameExists(data) {
			let curLevelData = this.$parent.data.filter(n => n.pid === data.pid);
			if (!this.addOrEdit && !this.isAddSub) {
				let curData = curLevelData.filter(n => n.name !== this.originalName);
				return curData.some(n => n.name === data.name);
			} else {
				return curLevelData.some(n => n.name === data.name);
			}
		},

		//提交表单数据
		handleSubmitForm() {
			this.$refs['form'].validate((valid) => {
				if (!valid) return false;
				if (this.judgeNameExists(this.formData)) {
					this.$showCustomMessage('warning', `已存在名为【${this.formData.name}】的数据，请重新输入`);
					return false;
				}
				this.submitFormRequest();
			});
		},

		//提交表单请求
		async submitFormRequest() {
			let params = this.formatFormParams();
			let callFunction = eval(this.addOrEdit || this.isAddSub ? addedConfig : updateConfig);
			let result = await callFunction(params).then((res) => res.data);
			if (result.code === '0') {
				this.$showCustomMessage('success', `${this.dialogTitle}成功`);
				this.$store.dispatch('getSiteConfig');
				this.$emit('finish');
				this.visible = false;
			}
		}
	}
}